package com.program.facesigninsystem.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.program.facesigninsystem.entity.ResponseModel;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;

public class ReqInterceptor extends HandlerInterceptorAdapter {

        /**
         * 一个拦截器
         * @param request
         * @param response
         * @param handler
         * @return
         * @throws Exception
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //得到请求头
            String Authorization = request.getHeader("Authorization");//获得token
            String token = null;
            if(Authorization != null)
            token = Authorization.substring(7);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            //如果token没有则返回
            if(token==null || token.length()==0){
                JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "无token，不允许访问！").toString());
                response.getWriter().append(jsonObject.toString()).flush();
                return false;
            }
            else {
                try{
                    Long currentTime = System.currentTimeMillis();
                    Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
                    Long expTime = JWT.decode(token).getClaim("exptime").asLong();
                    if(currentTime - generateTime > expTime) {
                        JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "token过期，请重新登录！").toString());
                        response.getWriter().append(jsonObject.toString()).flush();
                        return false;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    //验证失败
                    JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "token无效，不允许访问！").toString());
                    response.getWriter().append(jsonObject.toString()).flush();
                    return false;
                }
            }
            return super.preHandle(request, response, handler);
        }
}
